package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.ext.doman.SearchParams;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: brookpeng
 * @Date: 2022/2/17 16:27
 */
@Slf4j
@RestController
@RequestMapping("/api/courseList")
public class CourseListController extends BaseController {

    @PersistenceContext
    EntityManager entityManager;

    @PostMapping("/courseCenter")
    public Map<String, Object> getList(@RequestBody SearchParams searchParams) {

        // 设定状态启用
        boolean courseDisableFilter = true;
        // 设定状态名称
        String status = "已启用";

        String userId = getUserId();

        // 查询页面 courseCenter课程中心/myStudy我的学习
        String listType = searchParams.getListType();
        String keyWord = searchParams.getKeyWord();
        String developer = searchParams.getDeveloper();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp yearF = searchParams.getYearFrom();
        Timestamp yearT = searchParams.getYearTo();
        String yearFrom = null;
        String yearTo = null;
        if (yearF != null) {
            yearFrom = df.format(yearF);
        }
        if (yearT != null) {
            yearTo = df.format(yearT);
        }
        // 课程分类
        String courseClassification = searchParams.getCourseClassification();
        // 课程系列
        String courseSeries = searchParams.getCourseSeries();
        // 课程类别
        String courseType = searchParams.getCourseType();
        // 课程属性
        String courseAttribute = searchParams.getCourseAttribute();
        Integer pageNum = searchParams.getPageNum();
        Integer pageSize = searchParams.getPageSize();
        int startNum = 0;
        if (pageNum == null || pageSize == null) {
            pageNum = 0;
            pageSize = 10;
        } else {
            startNum = pageNum * pageSize;
        }
        // 课程中心表
        String kcqdTable = getBizObjectFacade().getTableName("kcqd");
        // 我的学习表
        String myStudy = getBizObjectFacade().getTableName("myStudy");
        //学习推送管理的子表
        String xxtskcqd = getBizObjectFacade().getTableName("xxtskcqd");

        StringBuilder selectList = new StringBuilder("SELECT T.* ");

        StringBuilder selectCount = new StringBuilder("SELECT COUNT(T.id) ");

        StringBuilder selectSql;
        if ("myStudy".equals(listType)) {
            selectSql = new StringBuilder("FROM `" + kcqdTable + "` T INNER JOIN `" + myStudy + "` T2 ON CONCAT(T.id,'" + userId + "') = T2.couseIdAndUserId ");
        } else if ("myActivity".equals(listType)) {
            //新逻辑
            selectSql = new StringBuilder("FROM `" + kcqdTable + "` T INNER JOIN `" + xxtskcqd + "` T2 on T.id = T2.kcbh and T2.parentId = '" + searchParams.getObjectId() + "'");
        } else {
            selectSql = new StringBuilder("FROM `" + kcqdTable + "` T ");
        }

        boolean where = false;
        boolean or = false;

        // 关键词
        if (StringUtils.isNotEmpty(keyWord)) {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
            selectSql.append("(T.courseName LIKE '%" + keyWord + "%' OR T.kcbh LIKE '%" + keyWord + "%') ");
            or = true;
        }
        // 开发人
        if (StringUtils.isNotEmpty(developer)) {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
            selectSql.append("T.kczkfr LIKE '%" + developer + "%' ");
            or = true;
        }
        // 入库年度
        if (StringUtils.isNotEmpty(yearFrom) && StringUtils.isNotEmpty(yearTo)) {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
            selectSql.append("(DATE_FORMAT(T.`year`,'%Y-%m-%d %H:%i:%s') >= '" + yearFrom + "' AND DATE_FORMAT(T.`year`,'%Y-%m-%d %H:%i:%s') <= '" + yearTo + "') ");
            or = true;
        } else if (StringUtils.isNotEmpty(yearFrom) && StringUtils.isEmpty(yearTo)) {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
            selectSql.append("DATE_FORMAT(T.`year`,'%Y-%m-%d %H:%i:%s') >= '" + yearFrom + "' ");
            or = true;
        } else if (StringUtils.isEmpty(yearFrom) && StringUtils.isNotEmpty(yearTo)) {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
//            selectSql.append("DATE_FORMAT(T.`year`,'%Y-%m-%d %H:%i:%s') <= '" + yearTo + "' ");
            // 改为时间点后，前端使用此字段传输参数，yearTo
            selectSql.append("DATE_FORMAT(T.`year`,'%Y-%m-%d %H:%i:%s') = '" + yearTo + "' ");
            or = true;
        } else {
            // do nothing
        }
        // 课程属性
        if (StringUtils.isEmpty(courseClassification) && StringUtils.isEmpty(courseSeries) &&
                StringUtils.isEmpty(courseType) && StringUtils.isEmpty(courseAttribute)) {
            // do nothing
        } else {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
            selectSql.append("( ");
            boolean andAppend = false;
            if (StringUtils.isNotEmpty(courseClassification)) {
                if (andAppend) {
                    selectSql.append("and ");
                }
                selectSql.append("T.modality LIKE '%" + courseClassification + "%' ");
                andAppend = true;
            }
            if (StringUtils.isNotEmpty(courseSeries)) {
                if (andAppend) {
                    selectSql.append("and ");
                }
                selectSql.append("T.series LIKE '%" + courseSeries + "%' ");
                andAppend = true;
            }
            if (StringUtils.isNotEmpty(courseType)) {
                if (andAppend) {
                    selectSql.append("and ");
                }
                selectSql.append("T.category LIKE '%" + courseType + "%' ");
                andAppend = true;
            }
            if (StringUtils.isNotEmpty(courseAttribute)) {
                if (andAppend) {
                    selectSql.append("and ");
                }
                selectSql.append("T.kcxl LIKE '%" + courseAttribute + "%' ");
                andAppend = true;
            }
            selectSql.append(") ");
            or = true;
        }
        // 停用课程条件
        if (courseDisableFilter) {
            if (!where) {
                selectSql.append("where ");
                where = true;
            }
            if (or) {
                selectSql.append("and ");
            }
            //selectSql.append("(T.kczt <> '" + status + "' OR T.kczt IS NULL) ");
            selectSql.append(" T.kczt ='" + status + "'");
            or = true;
        }

        StringBuilder limitSql = new StringBuilder("LIMIT " + startNum + "," + pageSize + " ");

        StringBuilder listSql = selectList.append(selectSql).append(limitSql);
        StringBuilder countSql = selectCount.append(selectSql);

        Map<String, Object> rst = new HashMap<>();
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(listSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        BigInteger singleResult = (BigInteger) entityManager.createNativeQuery(countSql.toString()).getSingleResult();

        for (Map<String, Object> stringObjectMap : resultList) {
            String id = MapUtils.getString(stringObjectMap, "id");
            BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcqd", id);
            Object attachment = bizObject.get("kcfm");
            stringObjectMap.put("kcfm", attachment);
        }

        rst.put("data", resultList);
        rst.put("total", singleResult.intValue());
        rst.put("errcode", 0);
        rst.put("errmsg", "获取数据成功");

        return rst;
    }
}
